package spring.boot.controller;

import javax.servlet.http.HttpSession;


import org.springframework.data.redis.core.RedisTemplate;
import spring.boot.po.AgentUserEntity;
import spring.boot.po.User;
import spring.boot.service.LoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.concurrent.locks.Lock;


@Controller
public class Login {
	@Autowired
	LoginService loginservice;

	@Autowired
	RedisTemplate redisTemplate;

	//登录信息校验方法
	@RequestMapping("/loginvalidate")
	public String loginvalidate(@RequestParam(value = "aid",defaultValue = "")Integer aid,@RequestParam(value = "uid",defaultValue = "") Integer uid,HttpSession httpSession){
		System.out.println("这是aid："+aid+"这是uid："+uid);

		if (aid!=null){
			httpSession.setAttribute("aid",aid);
			return "chatroom";
		}
		String getpwdbyname = loginservice.getpwdbyname(uid);
		System.out.println(getpwdbyname+":查到的密码");
		if(getpwdbyname!=null) {
			Integer uid1=loginservice.getUidbyname(uid);
			httpSession.setAttribute("uid", uid1);
			return "chatroom";
		}else
			return "fail";
	}

	@RequestMapping("/logout")
	public String logout(HttpSession httpSession){
		return "login";
	}

	@RequestMapping(value="/currentuser",method = RequestMethod.GET)
	@ResponseBody
	public User currentuser(HttpSession httpSession){

		Object uid = httpSession.getAttribute("uid");
		if (uid!=null){
			int i = Integer.parseInt(uid+"");

			String getnamebyid = loginservice.getnamebyid(i);
			httpSession.setAttribute("uid",null);
			return new User(i, getnamebyid);
		}
		Object aid = httpSession.getAttribute("aid");
		if (aid!=null){
			int i = Integer.parseInt(aid + "");
			AgentUserEntity getagent = loginservice.getagent(i);

			httpSession.setAttribute("aid",null);

			return new User(getagent.getAgentId(), getagent.getAgentName());

		}
		return null;
	}
}
